/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-leads
*
* @File name : LeadsService.java
*
* @Author : Administrator
*
* @Date : 2017年3月8日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月8日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.leads.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dto.SendTicket;
import org.marketing.common.dto.customerInfo.MemberDto;
import org.marketing.common.dto.leads.InsuranceDto;
import org.marketing.common.dto.leads.ThreadcarDto;
import org.marketing.common.dto.leads.TmFixCodeDto;
import org.marketing.common.dto.points.CustomerPointsDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.dto.showroom.BrandExhibitionDto;
import org.marketing.common.dto.showroom.PackageSimpleDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventLeadSendMessageDto;
import org.marketing.common.event.EventRecommandCarOrderInfoDTO;
import org.marketing.common.event.EventRecommandCarOrderedDTO;
import org.marketing.common.event.RecommandCarOrderedInvalidDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.MD5Util;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.ibm.icu.text.SimpleDateFormat;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.common.service.BaseService.MQChannelType;
import com.yonyou.gmmc.service.leads.constant.LeadsConstant;
import com.yonyou.gmmc.service.leads.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.service.leads.dao.TtCustomerPointsLogMapper;
import com.yonyou.gmmc.service.leads.dao.TtCustomerPointsMapper;
import com.yonyou.gmmc.service.leads.model.SaleInfo;
import com.yonyou.gmmc.service.leads.model.ThreadmqDto;
import com.yonyou.gmmc.service.leads.model.TtCustomerPoints;
import com.yonyou.gmmc.service.leads.model.TtCustomerPointsLog;

import tk.mybatis.mapper.entity.Example;

/**
 * @author yaohan
 * @date 2017年3月8日
 */
@Transactional
@Service("leadsService")
public class LeadsService {

	private Logger logger = Logger.getLogger(LeadsService.class);

	@Autowired
	private TmPotentialUserMapper tmpotentialusermapper;

	@Autowired
	private BaseService eventService;

	@Autowired
	private TtCustomerPointsMapper ttCustomerPointsMapper;

	@Autowired
	private TtCustomerPointsLogMapper ttCustomerPointsLogMapper;
	@Value("${SMS-pass}")
	private String smsPass;
	@Value("${SMS-key}")
	private String smsKey;
	@Value("${SMS_CDKEY}")
	private String SMS_CDKEY;
	@Value("${SMS_PASS}")
	private String SMS_PASS;
	@Value("${SMS_BASEURL}")
	private String SMS_BASEURL;

	@Value("${THREAD_DAY}")
	private String THREAD_DAY;

	/**
	 * 保存推荐购车
	 * 
	 * @author yaohan
	 * @param threadcardto
	 * @return map
	 */
	public Map<String, Object> saveThread(@RequestBody ThreadcarDto threadcardto, String openId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("errorCode", "0");
		try {
			// 通过openID查询userId
			Long userId2 = tmpotentialusermapper.queryUerId(openId);
			logger.info("查询出来的userId为：" + userId2);
			// 将userId插入实体类
			threadcardto.setUserId(userId2);
			// 判断推荐人今日推荐数是否满十条
			Long userId = threadcardto.getUserId();
			// 查询当日推荐条数
			int count = tmpotentialusermapper.selectThreadCount(userId);
			if (count >= 10) {
				// 今日推荐数已满十条，不允许推荐
				map.put("errorMsg", "今日推荐数已满");
			} else {
				// 今日推荐数不满十条，保存该推荐
				List<ThreadcarDto> list = tmpotentialusermapper.getSeq();
				for (ThreadcarDto threadcarDto2 : list) {
					threadcardto.setThreadId(threadcarDto2.getThreadId());
					tmpotentialusermapper.save(threadcardto);
					// 发送短信
					// logger.info("发送短信To：" + threadcardto.getFriendphone());
					// String s =
					// SmsHttpClient.sendSms(threadcardto.getFriendphone(),
					// "您的好友" + threadcardto.getUsername() + "为您推荐了广汽三菱"
					// + threadcardto.getRecommendedcars()
					// + "车型，凭此短信可到店深度试驾，地址："
					// + threadcardto.getAddress() + "，电话："
					// + threadcardto.getPhonenumber()
					// +
					// "。温馨提示：广汽三菱近期将通过4009773030专属服务电话与您联系。请你注意接听并配合回访",smsPass,smsKey,SMS_CDKEY,SMS_PASS,SMS_BASEURL);
					// logger.info("发送短信————End");
					// logger.info("返回码————" + s);
					// 判断是否为车主
					// List<MemberDto> memDto =
					// tmpotentialusermapper.queryUserOwner(openId);
					// if (memDto == null || memDto.size() == 0) {
					// // 不是车主
					// } else {
					// // 是车主
					// // 发送推荐购车积分（15分）
					// logger.info("推荐购车发积分_Start");
					// EventRecommandCarOrderInfoDTO etDto = new
					// EventRecommandCarOrderInfoDTO();
					// etDto.setFromUserId(threadcardto.getUserId().intValue());
					// etDto.setPhone(threadcardto.getUserphone());
					// etDto.setRecommandBizNo(threadcardto.getThreadId().toString());
					// logger.info("Content:" + etDto.toString());
					// // etDto.setToUserId(Integer.valueOf(""));
					// logger.info("USER_ID为：" + etDto.getToUserId());
					// BizEvent event = new BizEvent();
					// event.setEventKey("TJJF" + "-" +
					// etDto.getRecommandBizNo() + "-" + etDto.getPhone());
					// event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
					// event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_INFO_SEND);
					// event.setEventData(MapConverUtil.PO2Map(etDto));
					// String a = eventService.sendEvent2MQ(event);
					// logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + a);
					// logger.info("推荐购车发积分_End");
					// }
					// 发送事件到MQ——DCMS
					sendMessage2MQ(threadcardto);
					map.put("errorMsg", "推荐成功");
				}
			}
		} catch (Exception e) {
			logger.info("Exception:", e);
			map.put("errorCode", "1");
			map.put("errorMsg", e.getMessage());
		}
		return map;
	}

	
	/**
     * 获取保险公司
     * 
     * @author Administrator 
     * @date 2017年4月13日
     * @return
     */
    public List<InsuranceDto> getInsuranceMap() {

        return tmpotentialusermapper.getInsurance();

    }
	
	/**
	 * 发送推荐购车消息到mq
	 * 
	 * @param threadcardto
	 * @throws Exception
	 */
	public void sendMessage2MQ(ThreadcarDto threadcardto) throws Exception {
		IfMessage<List<EventLeadSendMessageDto>> l = new IfMessage<List<EventLeadSendMessageDto>>();
		List<EventLeadSendMessageDto> list = new ArrayList<EventLeadSendMessageDto>();
		EventLeadSendMessageDto ltSend = new EventLeadSendMessageDto();
		ltSend.setRecommendNo(threadcardto.getThreadId());
		ltSend.setName(threadcardto.getFriendname());
		ltSend.setMobile(threadcardto.getFriendphone());
		ltSend.setModelCode(threadcardto.getRecommendedcar());
		ltSend.setDealerCode(threadcardto.getRecommendedstore());
		ltSend.setReason(threadcardto.getRecommendedreasons());
		ltSend.setMemo(threadcardto.getUsername() + ":" + threadcardto.getUserphone());
		list.add(ltSend);
		l.setIfData(list);
		String time = String.valueOf(new Date().getTime());
		String transferNo = MD5Util.MD5("IC006" + time + CommonConstant.HTTP_CLUB_KEY);
		l.setIfCode("IC006");
		l.setOccurtime(time);
		l.setTransferNo(transferNo);
		l.setDataCnt(1);
		String s = eventService.sendMessage2MQ(MQChannelType.appRecommandOrder, JSON.toJSONString(l).toString());
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);

	}

	/**
	 * 根据品牌code或查询所有品牌车系数据
	 * 
	 * @author QianKun
	 * @date 2017年3月13日
	 * @param brandCode
	 * @return
	 */
	public List<BrandExhibitionDto> getBrandExhibitionData(String brandCode) {
		List<BrandExhibitionDto> dtoList = tmpotentialusermapper.queryBrandExhibitionData(brandCode);
		return dtoList;
	}

	/**
	 * @author LiuJun 根据车系code查询所有车型以及车型的配置-根据排量和变速箱类型
	 * @date 2017年1月3日
	 * @param seriesCode
	 * @param dealerCode
	 * @return
	 */
	public List<PackageSimpleDto> getPackageDataByDisplacementAndGearboxType(String seriesCode, String dealerCode) {
		if (CheckUtil.NullOrEmpty(seriesCode)) {
			logger.warn("getModelExhibitionData-seriesCode is null");
			throw new ServiceBizException("seriesCode is null");
		}
		List<PackageSimpleDto> packages = tmpotentialusermapper.queryPackageDataByDisplacementAndGearboxType(seriesCode,
				dealerCode);
		return packages;
	}

	/**
	 * 获取字典表 推荐理由 code和name
	 * 
	 * @return
	 */
	public List<TmFixCodeDto> getTscodename() {
		List<TmFixCodeDto> doList = tmpotentialusermapper.getTscode(1032);
		return doList;

	}

	/**
	 * 通过推荐人 userid friendname recommendedcar 查找推荐时间
	 * 
	 * @param threadcardto
	 * @return
	 */
	public List<ThreadcarDto> getCreatetime(String openId, String friendphone, String recommendedcar,
			String dealerCode) {
		List<ThreadcarDto> doList = tmpotentialusermapper.getCreatetime(openId, friendphone, recommendedcar,
				dealerCode);
		return doList;

	}

	/**
	 * 通过单号修改状态
	 * 
	 * @param recommendno
	 * @param status
	 * @return
	 */
	public void updateStatus(String recommendno, String status) {
		SaleInfo SaleInfo = new SaleInfo();
		SaleInfo.setRecommendNo(recommendno);
		SaleInfo.setStatus(status);
		tmpotentialusermapper.updateStatus(SaleInfo);

	}

	/**
	 * 推荐购车推送消息
	 * 
	 * @param threadmqdto
	 * @throws Exception
	 */
	public void maintainSend(ThreadmqDto threadmqdto) throws Exception {
		logger.info("推荐购车推送MQ_Start");
		EventRecommandCarOrderedDTO etDto = new EventRecommandCarOrderedDTO();
		etDto.setFromUserId(threadmqdto.getUserid());
		etDto.setToUserId(0);
		etDto.setPhone(threadmqdto.getUserphone());
		etDto.setRecommandBizNo(threadmqdto.getRecommandBizNo());
		etDto.setRecommandNum(threadmqdto.getRecommandNum());
		etDto.setSalesOrderNo("");
		logger.info("Content:" + etDto.getRecommandNum());
		BizEvent event = new BizEvent();
		event.setEventKey("TJGC" + threadmqdto.getRecommandBizNo() + threadmqdto.getRecommendedstate());
		event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
		event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_ORDERED);
		event.setEventData(MapConverUtil.PO2Map(etDto));
		String s = eventService.sendEvent2MQ(event);
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		logger.info("推荐购车推送MQ_End");
		// 发放卡券
		logger.info("根据车主ID去查潜客ID");
		Integer potentialUserId = tmpotentialusermapper.selectPotentialUserId(threadmqdto.getUserid());
		String dealerCode = tmpotentialusermapper.selectDealerById(potentialUserId);
		logger.info("自动发放卡券");
		SendTicket ticketDto = new SendTicket();
		ticketDto.setBizCode(1005);
		ticketDto.setTriggerCode(10051001);
		ticketDto.setUserId(potentialUserId);
		// logger.info("该用户的销售店为："+dealerCode);
		if (dealerCode != null) {
			ticketDto.setDealerCode(dealerCode);
		} else {
			ticketDto.setDealerCode("");
		}
		ticketDto.setBatchId("");
		ticketDto.setBizId(threadmqdto.getRecommandBizNo());
		BizEvent et = new BizEvent();
		et.setEventBizType(EventBizType.SEND_TICKET);
		et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
		et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new Date().getTime());
		et.setEventData(MapConverUtil.PO2Map(ticketDto));
		String x = eventService.sendEvent2MQ(et);
		logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
		/*
		 * //1代表推荐信息，2代表推荐留资 if("1".equals(threadmqdto.getState())){ } else
		 * if("2".equals(threadmqdto.getState())){
		 * EventRecommandInfoEffectiveDTO efDto=new
		 * EventRecommandInfoEffectiveDTO();
		 * efDto.setFromUserId(threadmqdto.getUserid());
		 * efDto.setPhone(threadmqdto.getUserphone());
		 * efDto.setRecommandBizNo(threadmqdto.getRecommandBizNo());
		 * efDto.setToUserId(0); BizEvent event = new BizEvent();
		 * event.setEventBizType(EventBizType.RECOMMAND_INFO);
		 * event.setEventBizStep(EventBizStep.RECOMMAND_INFO_EFFECTIVE);
		 * event.setEventData(MapConverUtil.PO2Map(efDto));
		 * eventService.sendEvent2MQ(event); }
		 */

	}

	/**
	 * 推荐购车线索无效
	 * 
	 * @author Administrator
	 * @date 2017年5月4日
	 * @param threadmqdto
	 * @throws Exception
	 */
	public void threadInvalidSend(ThreadmqDto threadmqdto) throws Exception {
		logger.info("推荐购车线索无效_Start");
		RecommandCarOrderedInvalidDTO etDto = new RecommandCarOrderedInvalidDTO();
		etDto.setFromUserId(threadmqdto.getUserid());
		etDto.setToUserId(0);
		etDto.setPhone(threadmqdto.getUserphone());
		etDto.setRecommandBizNo(threadmqdto.getRecommandBizNo());
		logger.info("Content:" + etDto.getRecommandBizNo());
		BizEvent event = new BizEvent();
		event.setEventKey("TJGCWX" + etDto.getRecommandBizNo() + '-' + etDto.getToUserId());
		event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
		event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_LEADS_INVALID);
		event.setEventData(MapConverUtil.PO2Map(etDto));
		String s = eventService.sendEvent2MQ(event);
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		logger.info("推荐购车线索无效_End");
	}

	/**
	 * 推荐购车推送消息
	 * 
	 * @param recommendno
	 * @return
	 */
	public List<ThreadmqDto> getThreadmq(String recommendno) {
		try {
			logger.info("推荐购车推送消息——Start");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String before = "";
			String after = "";
			String registDate = tmpotentialusermapper.selectUserRegistDate(recommendno);
			Date d = sdf.parse(registDate);
			Date now = new Date();
			int a = d.compareTo(now);
			while (a != 1) {
				after = sdf.format(d);
				d.setYear(d.getYear() + Integer.valueOf(THREAD_DAY));
				a = d.compareTo(now);
				before = sdf.format(d);
			}
			logger.info("时间：" + after);
			List<ThreadmqDto> ThreadmqDtolis = tmpotentialusermapper.getThreadmq(recommendno, after);
			for (ThreadmqDto threadmqDto : ThreadmqDtolis) {
				logger.info("推荐成功数为：" + threadmqDto.getRecommandNum());
				threadmqDto.setRecommandBizNo(recommendno);
				threadmqDto.setRecommendedstate("1");
				// threadmqDto.setState(threadmqDtoid.getState());
				logger.info("推送MQ");
				maintainSend(threadmqDto);
			}
			/*
			 * List<ThreadmqDto> ThreadmqDtolist=
			 * tmpotentialusermapper.getThreadid(recommendno); for (ThreadmqDto
			 * threadmqDtoid : ThreadmqDtolist) { //1代表推荐消息
			 * if("1".equals(threadmqDtoid.getState())){ //2代表推荐留资 }else
			 * if("2".equals(threadmqDtoid.getState())){ List<ThreadmqDto>
			 * ThreadmqDtolistqk=tmpotentialusermapper.getThreadqk(recommendno);
			 * for (ThreadmqDto threadmqDto : ThreadmqDtolistqk) {
			 * threadmqDto.setRecommandBizNo(recommendno);
			 * threadmqDto.setState(threadmqDtoid.getState());
			 * maintainSend(threadmqDto); } } }
			 */
			logger.info("推荐购车推送消息——END");
			return ThreadmqDtolis;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}

	}

	/**
	 * 推荐购车无效
	 * 
	 * @author Administrator
	 * @date 2017年5月4日
	 * @param recommendno
	 * @return
	 */
	public List<ThreadmqDto> getThreadInvalidmq(String recommendno) {
		List<ThreadmqDto> ThreadmqDtolis = new ArrayList<ThreadmqDto>();
		try {
			ThreadmqDtolis = tmpotentialusermapper.getThreadInfo(recommendno);
			if (ThreadmqDtolis.size() == 0) {
				logger.info("查不到该推荐单");
			} else {
				logger.info("推荐购车线索无效_Start");
				RecommandCarOrderedInvalidDTO etDto = new RecommandCarOrderedInvalidDTO();
				etDto.setFromUserId(ThreadmqDtolis.get(0).getUserid());
				logger.info("FromUserId--------------" + etDto.getFromUserId());
				etDto.setToUserId(0);
				etDto.setPhone(ThreadmqDtolis.get(0).getUserphone());
				// logger.info("Phone--------------" + etDto.getPhone());
				etDto.setRecommandBizNo(recommendno);
				// logger.info("RecommandBizNo--------------" +
				// etDto.getRecommandBizNo());
				logger.info("Content:" + etDto.getRecommandBizNo());
				BizEvent event = new BizEvent();
				event.setEventKey("TJGCWX" + etDto.getRecommandBizNo() + etDto.getToUserId());
				event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
				event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_LEADS_INVALID);
				event.setEventData(MapConverUtil.PO2Map(etDto));
				String s = eventService.sendEvent2MQ(event);
				logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
				logger.info("推荐购车线索无效_End");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return ThreadmqDtolis;
	}

	/**
	 * 判断朋友手机号和推荐店是否唯一
	 * 
	 * @param friendphone
	 * @param dealerCode
	 * @return
	 */
	public List<ThreadcarDto> getThreadPhone(String friendphone, String dealerCode) {
		List<ThreadcarDto> doList = tmpotentialusermapper.getThreadPhone(friendphone, dealerCode);
		return doList;

	}

	/**
	 * 根据推荐单号.判断是否车主
	 * 
	 * @param recommendno
	 * @return
	 */
	public boolean checkIsCarOwner(String recommendno) {
		logger.info("判断是否为车主");
		Map<String, Object> map = tmpotentialusermapper.queryCarOwnerByRecommendNo(recommendno);
		if (null != map) {
			return true;
		} else {
			return false;
		}
	}

	public boolean checkLead(String recommendno) {
		boolean result = false;
		logger.info("判断是否为已加分的线索");
		List<CustomerPointsDto> list = tmpotentialusermapper.queryLeads(recommendno);
		int size = list.size();
		logger.info("该推荐单在积分记录表中存在" + size + "条记录");
		if (size == 1) {
			String changeType = list.get(0).getChangeType();
			if (changeType.equals(LeadsConstant.LEAD_SUCCESS)) {
				result = true;
			} else {
				result = false;
			}
		} else {
			result = false;
		}
		return result;
	}

	/**
	 * 更新推荐单的线索状态
	 * 
	 * @author Administrator
	 * @date 2017年5月4日
	 * @param status
	 * @param recommendno
	 * @return
	 */
	public int updateThreadStatus(String status, String recommendno) {
		int i = 0;
		SaleInfo saleInfo = new SaleInfo();
		saleInfo.setStatus(status);
		saleInfo.setRecommendNo(recommendno);
		i = tmpotentialusermapper.updateThreadStatus(saleInfo);
		return i;
	}

	/**
	 * 查询推荐单的线索状态
	 * 
	 * @author Administrator
	 * @date 2017年5月4日
	 * @param recommendno
	 * @return
	 */
	public String selectThreadStatus(String recommendno) {
		return tmpotentialusermapper.selectThreadStatus(recommendno);
	}

	public Map<String, Object> Thread() {
		Map<String, Object> map = new HashMap<String, Object>();
		// map.put("errorCode", "0");
		logger.info("Start!");
		ThreadcarDto threadcardto = new ThreadcarDto();
		try {
			List<ThreadcarDto> list = tmpotentialusermapper.selectThread();
			for (ThreadcarDto threadcarDto2 : list) {
				logger.info("s");
				threadcardto.setThreadId(threadcarDto2.getThreadId());
				threadcardto.setAddress(threadcarDto2.getAddress());
				threadcardto.setFriendname(threadcarDto2.getFriendname());
				threadcardto.setFriendphone(threadcarDto2.getFriendphone());
				threadcardto.setNaiId(threadcarDto2.getNaiId());
				threadcardto.setPhonenumber(threadcarDto2.getPhonenumber());
				threadcardto.setRecommendedcar(threadcarDto2.getRecommendedcar());
				threadcardto.setUserphone(threadcarDto2.getUserphone());
				threadcardto.setUsername(threadcarDto2.getUsername());
				threadcardto.setUserId(threadcarDto2.getUserId());
				threadcardto.setTrunovertime(threadcarDto2.getTrunovertime());
				threadcardto.setThreadStatus(threadcarDto2.getThreadStatus());
				threadcardto.setThreadId(threadcarDto2.getThreadId());
				threadcardto.setState(threadcarDto2.getState());
				threadcardto.setSize(threadcarDto2.getSize());
				threadcardto.setRemark(threadcarDto2.getRemark());
				threadcardto.setRecommendedstores(threadcarDto2.getRecommendedstores());
				threadcardto.setRecommendedcars(threadcarDto2.getRecommendedcars());
				threadcardto.setRecommendedreasons(threadcarDto2.getRecommendedreasons());
				threadcardto.setRecommendedreasonss(threadcarDto2.getRecommendedreasonss());
				threadcardto.setRecommendedstate(threadcarDto2.getRecommendedstate());
				threadcardto.setRecommendedstore(threadcarDto2.getRecommendedstore());
				// 判断是否为车主
				List<MemberDto> memDto = tmpotentialusermapper.queryUserOwners(threadcardto.getUserId());
				if (memDto == null || memDto.size() == 0) {
					// 不是车主
				} else {
					// 是车主
					// 发送推荐购车积分（15分）
					logger.info("推荐购车发积分_Start");
					EventRecommandCarOrderInfoDTO etDto = new EventRecommandCarOrderInfoDTO();
					etDto.setFromUserId(threadcardto.getUserId().intValue());
					etDto.setPhone(threadcardto.getUserphone());
					etDto.setRecommandBizNo(threadcardto.getThreadId().toString());
					// logger.info("Content:" + etDto.toString());
					// etDto.setToUserId(Integer.valueOf(""));
					logger.info("USER_ID为：" + etDto.getToUserId());
					BizEvent event = new BizEvent();
					event.setEventKey("TJJF" + "-" + etDto.getRecommandBizNo() + "-" + etDto.getPhone());
					event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
					event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_INFO_SEND);
					event.setEventData(MapConverUtil.PO2Map(etDto));
					String a = eventService.sendEvent2MQ(event);
					logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + a);
					logger.info("推荐购车发积分_End");
				}
				// 发送事件到MQ——DCMS
				sendMessage2MQ(threadcardto);
				map.put("errorCode", "0");
				map.put("errorMsg", "推荐成功");
			}
		} catch (Exception e) {
			logger.info("Exception:", e);
			map.put("errorCode", "1");
			map.put("errorMsg", e.getMessage());
		}
		return map;
	}

	public Map<String, Object> backThread(String recommendno) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			logger.info("去查该单是否已经加分");
			// 创建Example
			Example example = new Example(TtCustomerPointsLog.class);
			example.createCriteria().andCondition("CHANGE_TYPE=", "10051001").andCondition("KEY_CODE=", recommendno);
			List<TtCustomerPointsLog> logList = ttCustomerPointsLogMapper.selectByExample(example);
			if (logList.size() == 0) {
				logger.info("未查到该单的加分记录，不作处理");
				map.put("errorCode", "0");
				map.put("errorMsg", "操作成功");
			} else {
				logger.info("有该推荐单的加分记录，应该扣分");
				// 查询用户当前积分日志情况
				TtCustomerPointsLog recordLog = new TtCustomerPointsLog();
				List<TtCustomerPointsLog> pointsLogList = ttCustomerPointsLogMapper
						.selectPointsLog(logList.get(0).getUserId());
				recordLog.setUserId(logList.get(0).getUserId());
				recordLog.setChangeBefore(pointsLogList.get(0).getChangeAfter());
				recordLog.setChangePoints(-logList.get(0).getChangePoints());
				Long pointsLog = pointsLogList.get(0).getChangeAfter() - logList.get(0).getChangePoints();
				recordLog.setChangeAfter(pointsLog);
				recordLog.setChangeType(10051005L);
				recordLog.setChangeReason("推荐购车已退车");
				recordLog.setKeyCode(recommendno);
				recordLog.setCreateBy(666666);
				recordLog.setCreateDate(new Date());
				logger.info("新增的参数为：" + recordLog);
				int i = ttCustomerPointsLogMapper.insertSelective(recordLog);
				logger.info("积分日志表新增" + i + "条减分记录");
				// 查询用户当前积分值
				TtCustomerPoints recordPoints = new TtCustomerPoints();
				List<TtCustomerPoints> pointsList = ttCustomerPointsMapper.selectPoints(logList.get(0).getUserId());
				Long points = pointsList.get(0).getPointsNum() - logList.get(0).getChangePoints();
				recordPoints.setPointsNum(points);
				recordPoints.setUpdateBy(666666);
				recordPoints.setUpdateDate(new Date());
				Example ex = new Example(TtCustomerPoints.class);
				logger.info("修改的参数为：" + recordPoints);
				ex.createCriteria().andCondition("USER_ID=", logList.get(0).getUserId());
				int s = ttCustomerPointsMapper.updateByExampleSelective(recordPoints, ex);
				logger.info("积分总表修改" + s + "条记录");
				map.put("errorCode", "0");
				map.put("errorMsg", "操作成功！");
			}
		} catch (Exception e) {
			logger.info("Exception:", e);
			map.put("errorCode", "1");
			map.put("errorMsg", e.getMessage());
		}
		return map;
	}

	public Map<String, Object> sendLeadsPointsToMq(String recommendno) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 根据单号去查推荐单相关信息
			List<ThreadmqDto> list = tmpotentialusermapper.getThreadInfo(recommendno);
			if (list.size() == 0) {
				logger.info("查不出该单状态");
			} else {
				// 发送推荐购车积分（15分）
				logger.info("推荐购车发积分_Start");
				EventRecommandCarOrderInfoDTO etDto = new EventRecommandCarOrderInfoDTO();
				etDto.setFromUserId(list.get(0).getUserid());
				logger.info("推荐人ID为：" + etDto.getFromUserId());
				etDto.setPhone(list.get(0).getUserphone());
				logger.info("推荐人手机为：" + etDto.getPhone());
				etDto.setRecommandBizNo(recommendno);
				// logger.info("单号为：" + etDto.getRecommandBizNo());
				// logger.info("Content:" + etDto.toString());
				// etDto.setToUserId(Integer.valueOf(""));
				logger.info("被推荐人USER_ID为：" + etDto.getToUserId());
				BizEvent event = new BizEvent();
				event.setEventKey("TJJF" + "-" + etDto.getRecommandBizNo() + "-" + etDto.getPhone());
				event.setEventBizType(EventBizType.RECOMMAND_CARORDER);
				event.setEventBizStep(EventBizStep.RECOMMAND_CARORDER_INFO_SEND);
				event.setEventData(MapConverUtil.PO2Map(etDto));
				String a = eventService.sendEvent2MQ(event);
				logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + a);
				logger.info("推荐购车发积分_End");
				resultMap.put("errorCode", "0");
				resultMap.put("errorMsg", "操作成功！");
				// 发放卡券
				logger.info("根据车主ID去查潜客ID");
				Integer potentialUserId = tmpotentialusermapper.selectPotentialUserId(list.get(0).getUserid());
				String dealerCode = tmpotentialusermapper.selectDealerById(potentialUserId);
				logger.info("自动发放卡券");
				SendTicket ticketDto = new SendTicket();
				ticketDto.setBizCode(1005);
				ticketDto.setTriggerCode(10051002);
				ticketDto.setUserId(potentialUserId);
				// logger.info("该用户的销售店为："+dealerCode);
				if (dealerCode != null) {
					ticketDto.setDealerCode(dealerCode);
				} else {
					ticketDto.setDealerCode("");
				}
				ticketDto.setBatchId("");
				ticketDto.setBizId(etDto.getRecommandBizNo());
				BizEvent et = new BizEvent();
				et.setEventBizType(EventBizType.SEND_TICKET);
				et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
				et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new Date().getTime());
				et.setEventData(MapConverUtil.PO2Map(ticketDto));
				String x = eventService.sendEvent2MQ(et);
				logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + x);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return resultMap;

	}

	public boolean checkTime(String recommendno) {
		Date threadDate = tmpotentialusermapper.selectThreadDate(recommendno);
		Date nowDate = new Date();
		Long time = nowDate.getTime() - threadDate.getTime();
		Long day = time / (24 * 60 * 60 * 1000);
		logger.info("推荐时间与当前时间相差：" + day + "天");
		if (day <= 365) {
			return true;
		} else {
			return false;
		}
	}

	public List<ThreadcarDto> myThread(String openId) {
		List<ThreadcarDto> list = new ArrayList<ThreadcarDto>();
		list = tmpotentialusermapper.selectMyThread(openId);
		return list;
	}
}
